# coding= utf-8

import pymongo
import sys
import time
import os
import xlsxwriter
from datetime import datetime


def remove_empty_elements(input_list):
    # 使用列表解析过滤掉空元素
    return [element for element in input_list if element]


def translate_domain(domain):
    dis = {1: 'us', 2: 'uk', 3: 'de', 4: 'fr', 5: 'jp', 6: 'ca', 8: 'it', 9: 'es', 10: 'in', 11: 'mx'}
    return dis.get(domain)


class Export:
    def __init__(self):
        self.where = sys.argv[1].split(',')
        # 连接MongoDB
        self.myclient = pymongo.MongoClient("mongodb://localhost:27017/")
        mydb = self.myclient["local_product"]
        self.my_product = mydb["amazon_product"]

    def export_xls(self):
        where = {'asin': {'$exists': True, '$ne': ''}}

        filter_list = remove_empty_elements(self.where)
        for i in filter_list:
            item = i.split('=')
            if item[1] and item[0]:
                if item[0] in ['domainId', 'star_level']:
                    where[item[0]] = int(item[1])
                elif item[0] in ['buy_box_current', 'reviews_rating', 'reviews_review_count', 'sales_rank_current']:
                    range = item[1].split('~')
                    if not range[0] == '' or not range[1] == '':
                        where[item[0]] = {}

                    if not range[0] == '':
                        where[item[0]]['$gte'] = int(range[0])
                    if not range[1] == '':
                        where[item[0]]['$lte'] = int(range[1])
                elif item[0] == 'task_id':
                    where['client_task_id'] = item[1]
                else:
                    where[item[0]] = item[1]

        # 创建文件地址
        dir = time.strftime('%Y-%m', time.localtime(time.time()))
        date = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
        dir_path = './upload/local_product/' + dir + '/'
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
        path = dir_path + '-' + date + '.xlsx'
        xls = xlsxwriter.Workbook(path)
        sht1 = xls.add_worksheet('sheet1')
        head_style = xls.add_format(
            {'color': 'white', 'align': 'center', 'bg_color': '#008B45', 'bold': True,
             'font_name': 'Times New Roman, fantasy', 'valign': 'vcenter'})
        body_style = xls.add_format({'valign': 'vcenter', 'align': 'center', 'font_name': 'Times New Roman'})
        sht1.set_row(0, 25)

        head = []
        for col, result in enumerate(self.my_product.find(where)):
            sht1.set_row(col + 1, 50)
            for f_index, f in enumerate(result):
                value = result[f]
                if f not in head:
                    head.append(f)
                if f == '_id':
                    value = str(value).replace('-', '')
                    sht1.write(col + 1, f_index, value, body_style)
                elif f == 'categoryTree' and value:
                    category = []
                    for i in value:
                        category.append(i['name'])
                    cate_str = ' > '.join(category)
                    sht1.write(col + 1, f_index, cate_str, body_style)
                elif f == 'domainId':
                    sht1.write(col + 1, f_index, translate_domain(value), body_style)
                elif f in ['lastUpdate', 'lastPriceChange', 'created_at', 'mark_time'] and value:
                    # 将时间戳转换为datetime对象
                    dt_object = datetime.fromtimestamp(value)

                    # 将datetime对象格式化为字符串
                    formatted_date = dt_object.strftime('%Y-%m-%d %H:%M')

                    sht1.write(col + 1, f_index, formatted_date, body_style)
                else:
                    sht1.write(col + 1, f_index, value, body_style)

        sht1.set_column(0, len(head), 20)
        # 添加表头
        for index, h_item in enumerate(head):
            sht1.write(0, index, h_item, head_style)

        # 输出文件地址
        xls.close()
        self.myclient.close()
        path = 'https://xp-local.wszzl.cn/' + path
        # path = 'http://amazon.mark/' + path
        print(path)


export = Export()
export.export_xls()
# export.test()
exit()
